package com.wy.component.ldap;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

import com.wy.component.properties.PropertiesUtil;

public class LdapUserAuth {
	static PropertiesUtil p = new PropertiesUtil();
	private static String URL = "";
	private static String BASEDN = "";
	private static String FACTORY = "";
	private static LdapContext ctx = null;
	private static Hashtable env = null;
	private static Control[] connCtls = null;

	public LdapUserAuth() throws FileNotFoundException, IOException {
		URL = p.getAppProperties("LDAP_URL");
		BASEDN = p.getAppProperties("LDAP_BASEDN");
		FACTORY = p.getAppProperties("LDAP_FACTORY");
	}
	
	@SuppressWarnings("unchecked")
	private static void LDAP_connect() {
		env = new Hashtable();
		env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
		env.put(Context.PROVIDER_URL, URL + BASEDN);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");

		try {
			ctx = new InitialLdapContext(env, connCtls);
		} catch (javax.naming.AuthenticationException e) {
			System.out.println("Authentication faild: " + e.toString());
		} catch (Exception e) {
			System.out.println("Something wrong while authenticating: "
					+ e.toString());
		}
	}

	public static String authenricateUser(String ID, String password) {
		boolean valide = false;
		LDAP_connect();
		try {
			ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, ID);
			ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
			ctx.reconnect(connCtls);
			valide = true;
		} catch (Exception e) {
			valide = false;
		}
		if (valide) {
			return "true";
		} else {
			return "false";
		}
	}

	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		try {
			System.out.println(LdapHelperNew.authenticate("20112060505",LdapMd5.Md5Encode("103140")));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
}
